//// UserController.java
//package com.xiaocikuai.smallchunks.controller.User;
//
//import com.xiaocikuai.smallchunks.entity.User.*;
//import com.xiaocikuai.smallchunks.config.jwt.JwtUtils;
//import com.xiaocikuai.smallchunks.utils.SessionListener;
//import com.xiaocikuai.smallchunks.utils.resultd.PageResult;
//import com.xiaocikuai.smallchunks.utils.resultd.Resultd;
//import com.xiaocikuai.smallchunks.service.User.UserService;
//import jakarta.annotation.Resource;
//import jakarta.servlet.http.HttpServletResponse;
//import jakarta.servlet.http.HttpSession;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///*
//* 用户相关
//* */
//@RestController
//@RequestMapping("/api/user")
//@CrossOrigin
//public class UserController {
//
//    @Resource
//    private UserService userService;
//
//    @Resource
//    private SessionListener sessionListener;
//
//
//   //用户注册
//    @PostMapping("/register")
//    public Resultd registerUser(@RequestHeader("Authorization") String token, @RequestBody User user) {
//
//        String registrationResult = userService.registerUser(user);
//        if (registrationResult.equals("success")) {
//            return Resultd.ok().data("info", "注册成功");
//        } else {
//            return Resultd.error().data("info", registrationResult);
//        }
//    }
//
//
//    //用户登录
//    @PostMapping("/login")
//    public Resultd login(@RequestBody Login login, HttpServletResponse response) {
//        try {
//            if (login.getMode() == 0) {
//                String loginResult = userService.loginWithUsernameAndPassword(login, response);
//                if (loginResult.equals("success")) {
//                    String token = JwtUtils.generateToken(login.getUsername());
//                    userService.addTokenCookie(response, token);
//
//                    return Resultd.ok().data("token", token);
//                } else {
//                    return Resultd.error().data("token", loginResult);
//                }
//            } else if (login.getMode() == 1) {
//                String loginResult = userService.loginWithCode(login);
//                if (loginResult.equals("success")) {
//                    String token = JwtUtils.generateToken(login.getUsername());
//                    userService.addTokenCookie(response, token);
//
//                    return Resultd.ok().data("token", token);
//                } else {
//                    return Resultd.error().data("token", loginResult);
//                }
//            }
//
//            return Resultd.error().message("无效的登录模式");
//        } catch (Exception e) {
//            // 捕获所有异常并返回错误信息
//            return Resultd.error().message("登录失败：" + e.getMessage());
//        }
//    }
//
//
//
//
//    //用户分页
//    @PostMapping("/users")
//    public Resultd getUsersPage(@RequestBody UserQuery userQuery) {
//        PageResult<UserVO> pageResult = userService.page(userQuery.getPage(), userQuery.getSize());
//        return Resultd.ok()
//                .data("info", pageResult.getRecords())
//                .data("totalPages", pageResult.getTotalPages()).data("total",pageResult.getTotal());
//    }
//
//    // 按条件查询用户分页
//    @GetMapping("/selectusers")
//    public Resultd searchAndPageUsers(@RequestHeader("Authorization") String token,@RequestBody UserQuery userQuery) {
//        PageResult<UserVO> pageResult = userService.searchAndPage(userQuery, userQuery.getPage(), userQuery.getSize());
//        return Resultd.ok()
//                .data("info", pageResult.getRecords())
//                .data("totalPages", pageResult.getTotalPages()).data("total",pageResult.getTotalPages());
//    }
//
//
//    //用户签到
//    @PostMapping("/sign")
//    public Resultd userSign(@RequestHeader("Authorization") String token) {
//        Sign signs = userService.userSign(token);
//        if (signs != null){
//            return Resultd.ok().data("info",signs);
//        }else {
//            return Resultd.error().data("info","签到失败");
//        }
//
//    }
//
//
//    //请求获取用户积分
//    @PostMapping("/getIntegral")
//    public Resultd getIntegral(@RequestHeader("Authorization") String token) {
//        return Resultd.ok().data("info",userService.getIntegral(token));
//    }
//
//    //返回用户所有信息
//    @PostMapping("/getUser")
//    public Resultd getUser(@RequestHeader("Authorization") String token) {
//        return Resultd.ok().data("info",userService.getUser(token));
//    }
//
//    //用户今日是否签到
//    @PostMapping("/getIsSign")
//    public Resultd getIsSign(@RequestHeader("Authorization") String token) {
//        return Resultd.ok().data("info",userService.getIsSign(token));
//    }
//
//    //获取在线用户信息
//    @GetMapping("/onlineUsers")
//    public Resultd getOnlineUsers(HttpServletResponse response) {
//        Map<String, Object> onlineUsersInfo = userService.getOnlineUsersInfo();
//        return Resultd.ok().data("onlineUsersInfo", onlineUsersInfo);
//    }
//
//    @GetMapping("/onlineUsersInfo")
//    public Resultd getOnlineUsersByMode(@PathVariable int mode) {
//        List<UserOnline> users = null;
//        switch (mode) {
//            case 0:
//                users = userService.getTotalOnlineUsers();
//                break;
//            case 1:
//                users = userService.getAppOnlineUsers();
//                break;
//            case 2:
//                users = userService.getMiniProgramOnlineUsers();
//                break;
//            case 3:
//                users = userService.getWebsiteOnlineUsers();
//                break;
//            case 4:
//                users = userService.getUnknownPlatformOnlineUsers();
//                break;
//            default:
//                return Resultd.error().message("Invalid mode specified");
//        }
//        return Resultd.ok().data("onlineUsers", users);
//    }
//
//    //网站登录的统计
//    @PostMapping("/online")
//    public  Resultd getUserByUserNameAndPassword(@RequestBody UserOnline userOnline) {
//
//        try {
////            UserVO users = userService.getUser(token);
//            sessionListener.addUserOnline(userOnline.getUsername(), userOnline.getDevice());
//            return Resultd.ok().data("onlineUsers", "success");
//        } catch (Exception e) {
//            return Resultd.error().data("info",e);
//        }
//
//    }
//
//
//
//
//}
// UserController.java
package com.xiaocikuai.smallchunks.controller.User;

import com.xiaocikuai.smallchunks.entity.User.*;
import com.xiaocikuai.smallchunks.config.jwt.JwtUtils;
import com.xiaocikuai.smallchunks.utils.ExcelUtil;
import com.xiaocikuai.smallchunks.utils.JWTservice.JwtService;
import com.xiaocikuai.smallchunks.utils.SessionListener;
import com.xiaocikuai.smallchunks.utils.resultd.PageResult;
import com.xiaocikuai.smallchunks.utils.resultd.Resultd;
import com.xiaocikuai.smallchunks.service.User.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * 用户相关
 * */
@Api(tags = "用户控制器")
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private SessionListener sessionListener;

    @Resource
    private JwtService jwtService;

    @Resource
    private  ExcelUtil excelUtil;

    // 用户注册
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "body")
    })
    public Resultd registerUser(@RequestHeader("Authorization") String token, @RequestBody User user) {

        String registrationResult = userService.registerUser(user);
        if (registrationResult.equals("success")) {
            return Resultd.ok().data("info", "注册成功");
        } else {
            return Resultd.error().data("info", registrationResult);
        }
    }

    // 用户登录
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "login", value = "登录信息", required = true, dataType = "Login", paramType = "body"),
            @ApiImplicitParam(name = "response", value = "HttpServletResponse 对象", required = true, dataType = "HttpServletResponse", paramType = "body")
    })
    public Resultd login(@RequestBody Login login, HttpServletResponse response) {
        try {
            if (login.getMode() == 0) {
                String loginResult = userService.loginWithUsernameAndPassword(login, response);
                if (loginResult.equals("success")) {
                    String token = JwtUtils.generateToken(login.getUsername());
                    userService.addTokenCookie(response, token);
                    return Resultd.ok().data("token", token);
                } else {
                    return Resultd.error().data("info", loginResult);
                }
            } else if (login.getMode() == 1) {

                String loginResult = userService.loginWithCode(login);
                if (loginResult.equals("success")) {
                    String token = JwtUtils.generateToken(login.getUsername());
                    userService.addTokenCookie(response, token);

                    return Resultd.ok().data("token", token);
                } else {
                    return Resultd.error().data("info", loginResult);
                }
            }

            return Resultd.error().message("无效的登录模式");
        } catch (Exception e) {
            // 捕获所有异常并返回错误信息
            return Resultd.error().message("登录失败：" + e.getMessage());
        }
    }

    // 用户分页
    @ApiOperation(value = "获取用户分页")
    @PostMapping("/users"       )
    @ApiImplicitParam(name = "userQuery", value = "用户查询条件", required = true, dataType = "UserQuery", paramType = "body")
    public Resultd getUsersPage(@RequestBody UserQuery userQuery) {
        PageResult<UserVO> pageResult = userService.page(userQuery.getPage(), userQuery.getSize());
        return Resultd.ok()
                .data("info", pageResult.getRecords())
                .data("totalPages", pageResult.getTotalPages()).data("total",pageResult.getTotal());
    }

    // 按条件查询用户分页
    @ApiOperation(value = "按条件查询用户分页")
    @GetMapping("/selectusers")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "userQuery", value = "用户查询条件", required = true, dataType = "UserQuery", paramType = "body")
    })
    public Resultd searchAndPageUsers(@RequestHeader("Authorization") String token,@RequestBody UserQuery userQuery) {
        PageResult<UserVO> pageResult = userService.searchAndPage(userQuery, userQuery.getPage(), userQuery.getSize());
        return Resultd.ok()
                .data("info", pageResult.getRecords())
                .data("totalPages", pageResult.getTotalPages()).data("total",pageResult.getTotalPages());
    }

    // 用户签到
    @ApiOperation(value = "用户签到")
    @PostMapping("/sign")
    @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header")
    public Resultd userSign(@RequestHeader("Authorization") String token) {
        Sign signs = userService.userSign(token);
        if (signs!= null){
            return Resultd.ok().data("info",signs);
        }else {
            return Resultd.error().data("info","签到失败");
        }

    }

    // 请求获取用户积分
    @ApiOperation(value = "请求获取用户积分")
    @PostMapping("/getIntegral")
    @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header")
    public Resultd getIntegral(@RequestHeader("Authorization") String token) {
        return Resultd.ok().data("info",userService.getIntegral(token));
    }

    // 返回用户所有信息
    @ApiOperation(value = "返回用户所有信息")
    @PostMapping("/getUser")
    @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header")
    public Resultd getUser(@RequestHeader("Authorization") String token) {

        if(userService.getUser(token)==null) {
            return Resultd.error().data("info", "获取失败");
        }else {
            return Resultd.ok().data("info",userService.getUser(token));
        }
    }

    // 用户今日是否签到
    @ApiOperation(value = "用户今日是否签到")
    @PostMapping("/getIsSign")
    @ApiImplicitParam(name = "token", value = "授权令牌", required = true, dataType = "String", paramType = "header")
    public Resultd getIsSign(@RequestHeader("Authorization") String token) {
        return Resultd.ok().data("info",userService.getIsSign(token));
    }

    // 获取在线用户信息
    @ApiOperation(value = "获取在线用户信息")
    @GetMapping("/onlineUsers")
    public Resultd getOnlineUsers(HttpServletResponse response) {
        Map<String, Object> onlineUsersInfo = userService.getOnlineUsersInfo();
        return Resultd.ok().data("onlineUsersInfo", onlineUsersInfo);
    }

    @ApiOperation(value = "根据模式获取在线用户")
    @PostMapping("/onlineUsersInfo")
    @ApiImplicitParam(name = "mode", value = "模式（0 - 全部，1 - APP，2 - 小程序，3 - 网站，4 - 未知平台）", required = true, dataType = "int", paramType = "path")
    public Resultd getOnlineUsersByMode(Login mode) {
        List<UserOnline> users = new ArrayList<>();
        switch (mode.getMode()) {
            case 0:
                users = userService.getTotalOnlineUsers();
                break;
            case 1:
                users = userService.getAppOnlineUsers();
                break;
            case 2:
                users = userService.getMiniProgramOnlineUsers();
                break;
            case 3:
                users = userService.getWebsiteOnlineUsers();
                break;
            case 4:
                users = userService.getUnknownPlatformOnlineUsers();
                break;
            default:
                return Resultd.error().message("Invalid mode specified");
        }
        return Resultd.ok().data("onlineUsers", users);
    }

    // 网站登录的统计
    @ApiOperation(value = "网站登录统计")
    @PostMapping("/online")
    @ApiImplicitParam(name = "userOnline", value = "用户在线信息", required = true, dataType = "UserOnline", paramType = "body")
    public Resultd getUserByUserNameAndPassword(@RequestHeader("Authorization") String token,@RequestBody UserOnline userOnline) {
        userOnline.setUsername(jwtService.deconstruction(token).getUsername());
        try {
            sessionListener.addUserOnline(userOnline.getUsername(), userOnline.getDevice());
            return Resultd.ok().data("onlineUsers", "success");
        } catch (Exception e) {
            return Resultd.error().data("info",e);
        }

    }



    // 上传用户头像
    @ApiOperation(value = "上传用户头像")
    @PostMapping("/updateAvatar")
    public Resultd updateAvatar(@RequestHeader("Authorization") String token, @RequestParam("file") MultipartFile file){
        if ( userService.updateAvatar(file,token)) {
            return Resultd.ok().data("info","添加成功");
        } else {
            return Resultd.error().data("info","添加失败");
        }
    }

    @ApiOperation(value = "更新用户昵称")
    @PostMapping("/updateNickName")
    public Resultd updateNickName(@RequestHeader("Authorization") String token, @RequestBody User user) {
        if (userService.updateNickName(user.getNickname(),token)) {
            return Resultd.ok().data("info", "更新成功");
        } else {
            return Resultd.error().data("info", "更新失败");
        }
    }

    @ApiOperation(value = "更新用户密码")
    @PostMapping("/updatePassword")
    public Resultd updatePassword(@RequestHeader("Authorization") String token, @RequestBody User user) {
        if (userService.updatePassword(user.getPassword(),token)) {
            return Resultd.ok().data("info", "更新成功");
        } else {
            return Resultd.error().data("info", "更新失败");
        }
    }



    @ApiOperation(value = "申请加入我们")
    @PostMapping("/askSales")
    public Resultd askSales(@RequestHeader("Authorization") String token,@RequestBody User user) {
        String result = userService.askSales(token,user);
        if (result.equals("success")) {
            return Resultd.ok().data("info", "申请成功，请等待审核");
        } else {
            return Resultd.error().data("info",result);
        }
    }

    @ApiOperation(value = "通过审核")
    @PostMapping("/passSales")
    public Resultd passSales(@RequestHeader("Authorization") String token,@RequestBody User user) {

        if (userService.passSales(user.getUid())) {
            return Resultd.ok().data("info", "审核通过");
        } else {
            return Resultd.error().data("info", "失败");
        }
    }


    @ApiOperation(value="获取分销员")
    @PostMapping("/selectQuary")
    public Resultd selectQuary(@RequestHeader("Authorization") String token)
    {
        List<User> list = userService.selectQuary();
        if(list==null || list.isEmpty())
        {
            return Resultd.error().data("info","获取分销员失败");
        }
        return Resultd.ok().data("info",list);
    }

    @ApiOperation(value = "申请提现")
    @PostMapping("/askPayouts")
    public Resultd askPayouts(@RequestHeader("Authorization") String token,@RequestBody MemberSale memberSale) {
        String res = userService.askPayouts(memberSale.getMoney(),token,memberSale.getOpenId());
        if (res.equals("申请提现成功")) {
            return Resultd.ok().data("info", res);
        } else {
            return Resultd.error().data("info", res);
        }
    }


    @ApiOperation(value = "通过提现申请")
    @PostMapping("/passPayouts")
    public Resultd passPayouts(@RequestHeader("Authorization") String token,@RequestBody List<MemberSale> memberSales) {
        return Resultd.ok().data("info", userService.passPayouts(memberSales));
    }


    @ApiOperation(value = "获取我的分销明细")
    @PostMapping("/SelectMemberSale")
    public Resultd SelectMemberSale(@RequestHeader("Authorization") String token)
    {
        List<MemberSale> list = userService.selectMemberSale(token);
        if(list==null || list.isEmpty())
        {
            return Resultd.error().data("info","获取失败");
        }
        return Resultd.ok().data("info",list);
    }

    @ApiOperation(value = "查询未审批提现")
    @PostMapping("/SelectMember")
    public Resultd SelectMember(@RequestHeader("Authorization") String token)
    {
        List<MemberSale> list =  userService.selectMember();
        if(list == null || list.isEmpty())
        {
            return Resultd.error().data("info","暂无");
        }
        return Resultd.ok().data("info",list);
    }

    @ApiOperation(value = "获取今日收益")
    @PostMapping("/getTodayPayouts")
    public Resultd getTodayPayouts(@RequestHeader("Authorization") String token) {
        return Resultd.ok().data("info",userService.getTodayPayouts(token));
    }

    @ApiOperation(value = "获取昨日收益")
    @PostMapping("/getYesterdayPayouts")
    public Resultd getYesterdayPayouts(@RequestHeader("Authorization") String token) {
        return Resultd.ok().data("info",userService.getYesterdayPayouts(token));
    }

    @PostMapping("/testInsert")
    public Resultd testInsert(@RequestHeader("Authorization") String token,@RequestBody User user) {
        return Resultd.ok().data("info",userService.testInsert(user));
    }



    @PostMapping("/getExcel")
    public Resultd getExcel(@RequestHeader("Authorization") String token) {
        return Resultd.ok().data("info", excelUtil.getExcel());
    }



}

